document.addEventListener('DOMContentLoaded', function() {
    // 轮播图功能
    const slides = document.querySelectorAll('.slide');
    const dots = document.querySelectorAll('.dot');
    const prevBtn = document.querySelector('.prev');
    const nextBtn = document.querySelector('.next');
    let currentSlide = 0;
    let slideInterval;

    // 初始化轮播图
    function initSlider() {
        if (slides.length === 0) return;
        
        slides[currentSlide].classList.add('active');
        dots[currentSlide].classList.add('active');
        
        slideInterval = setInterval(nextSlide, 3000);
    }

    // 切换到下一张
    function nextSlide() {
        goToSlide((currentSlide + 1) % slides.length);
    }

    // 切换到上一张
    function prevSlide() { 
        goToSlide((currentSlide - 1 + slides.length) % slides.length);
    }

    // 跳转到指定幻灯片
    function goToSlide(n) {
        slides[currentSlide].classList.remove('active');
        dots[currentSlide].classList.remove('active');
        
        currentSlide = n;
        
        slides[currentSlide].classList.add('active');
        dots[currentSlide].classList.add('active');
        
        // 重置计时器
        clearInterval(slideInterval);
        slideInterval = setInterval(nextSlide, 5000);
    }

    // 事件监听
    prevBtn.addEventListener('click', prevSlide);
    nextBtn.addEventListener('click', nextSlide);
    
    dots.forEach((dot, index) => {
        dot.addEventListener('click', () => goToSlide(index));
    });

    // 初始化轮播图
    initSlider();

    // 登录模态框功能
    const loginLink = document.getElementById('login-link');
    const loginModal = document.getElementById('login-modal');
    const closeBtn = document.querySelector('.close');

    loginLink.addEventListener('click', function(e) {
        e.preventDefault();
        loginModal.style.display = 'block';
    });

    closeBtn.addEventListener('click', function() {
        loginModal.style.display = 'none';
    });

    window.addEventListener('click', function(e) {
        if (e.target === loginModal) {
            loginModal.style.display = 'none';
        }
    });


 // 注册功能
const registerLink = document.querySelector('.register-link');
const registerModal = document.getElementById('register-modal');
const toLoginLink = document.getElementById('to-login');
const sendCodeBtn = document.querySelector('.btn-send-code');

// 打开注册模态框
function showRegisterModal() {
    registerModal.style.display = 'block';
}

// 关闭注册模态框
function hideRegisterModal() {
    registerModal.style.display = 'none';
}

// 注册链接点击事件
if (registerLink) {
    registerLink.addEventListener('click', function(e) {
        e.preventDefault();
        hideLoginModal();
        showRegisterModal();
    });
}

// 注册模态框关闭按钮
registerModal.querySelector('.close').addEventListener('click', hideRegisterModal);

// 点击"已有账号"跳转到登录
toLoginLink.addEventListener('click', function(e) {
    e.preventDefault();
    hideRegisterModal();
    showLoginModal();
});

// 发送验证码功能
sendCodeBtn.addEventListener('click', function() {
    let countdown = 60;
    this.disabled = true;
    this.textContent = `${countdown}秒后重发`;
    
    const timer = setInterval(() => {
        countdown--;
        this.textContent = `${countdown}秒后重发`;
        
        if (countdown <= 0) {
            clearInterval(timer);
            this.disabled = false;
            this.textContent = '获取验证码';
        }
    }, 1000);
});

// 注册表单提交
const registerForm = document.getElementById('register-form');
if (registerForm) {
    registerForm.addEventListener('submit', function(e) {
        e.preventDefault();
        alert('注册成功！');
        hideRegisterModal();
        showLoginModal();
    });
}

// 点击模态框外部关闭
registerModal.addEventListener('click', function(e) {
    if (e.target === registerModal) {
        hideRegisterModal();
    }
});

// 辅助函数
function showLoginModal() {
    loginModal.style.display = 'block';
}

function hideLoginModal() {
    loginModal.style.display = 'none';
}

// 新人专区按钮交互
document.querySelectorAll('.new-user-card .btn').forEach(button => {
    button.addEventListener('click', function() {
        const productName = this.closest('.new-user-card').querySelector('h4').textContent;
        alert(`已领取${productName}，请到账户中心查看`);
        
        // 按钮状态变化
        this.textContent = '已领取';
        this.style.backgroundColor = '#4CAF50';
        
        setTimeout(() => {
            this.textContent = this.textContent.includes('领取') ? '立即领取' : '立即抢购';
            this.style.backgroundColor = '#c7000b';
        }, 2000);
    });
});

// 手机产品购买按钮交互
document.querySelectorAll('.product-card .btn, .featured-btn').forEach(button => {
    button.addEventListener('click', function() {
        const productCard = this.closest('.product-card, .featured-product');
        const productName = productCard.querySelector('h4, h3').textContent;
        const productPrice = productCard.querySelector('.product-price, .featured-price').textContent;
        
        // 模拟添加到购物车
        alert(`已将 ${productName} (${productPrice}) 加入购物车`);
        
        // 按钮反馈效果
        this.textContent = '已添加';
        this.style.backgroundColor = '#4CAF50';
        
        setTimeout(() => {
            this.textContent = '立即购买';
            this.style.backgroundColor = '#c7000b';
        }, 2000);
    });
});


    // 购物车功能
    // const addToCartButtons = document.querySelectorAll('.add-to-cart');
    // const cartCount = document.querySelector('.cart-count');
    // let cartItems = 0;

    // addToCartButtons.forEach(button => {
    //     button.addEventListener('click', function() {
    //         cartItems++;
    //         cartCount.textContent = cartItems;
            
    //         // 添加动画效果
    //         this.textContent = '已添加';
    //         this.style.backgroundColor = '#4CAF50';
            
    //         setTimeout(() => {
    //             this.textContent = '加入购物车';
    //             this.style.backgroundColor = '#f5f5f5';
    //         }, 1000);
    //     });
    // });

    // 购物车数据
let cartItems = [];

// 购物车功能
const addToCartButtons = document.querySelectorAll('.add-to-cart');
const cartCount = document.querySelector('.cart-count');
const cartLink = document.querySelector('.cart a');
const cartPage = document.getElementById('cart-page');
const cartEmpty = document.getElementById('cart-empty');
const cartItemsContainer = document.getElementById('cart-items');
const cartItemsList = document.getElementById('cart-items-list');
const cartTotal = document.getElementById('cart-total');
const continueShoppingBtn = document.getElementById('continue-shopping');
const checkoutBtn = document.getElementById('checkout-btn');

// 显示购物车页面
function showCartPage() {
    const cartPage = document.getElementById('cart-page');
    cartPage.style.display = 'block';
    
    // 强制重绘
    void cartPage.offsetWidth;
    
    // 添加active类触发动画
    cartPage.classList.add('active');
    
    // 更新购物车内容
    updateCartDisplay();
}

// 隐藏购物车页面
function hideCartPage() {
    const cartPage = document.getElementById('cart-page');
    cartPage.classList.remove('active');
    
    // 动画结束后隐藏
    setTimeout(() => {
        cartPage.style.display = 'none';
    }, 300);
}

// 更新购物车显示
function updateCartDisplay() {
    // 更新购物车数量显示
    cartCount.textContent = cartItems.length;
    
    // 计算总价（无论是否有商品都计算）
    let total = 0;
    cartItems.forEach(item => {
        total += item.price * item.quantity;
    });
    
    // 根据购物车是否为空显示不同内容
    if (cartItems.length === 0) {
        cartEmpty.style.display = 'block';
        cartItemsContainer.style.display = 'none';
        cartTotal.textContent = '¥0'; // 明确设置空购物车总价为0
    } else {
        cartEmpty.style.display = 'none';
        cartItemsContainer.style.display = 'block';
        
        // 清空现有商品列表
        cartItemsList.innerHTML = '';
        
        // 重新渲染所有商品
        cartItems.forEach((item, index) => {
            const subtotal = item.price * item.quantity;
            
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td>
                    <div class="cart-item">
                        <img src="${item.image}" alt="${item.name}">
                        <div class="cart-item-info">
                            <h4>${item.name}</h4>
                        </div>
                    </div>
                </td>
                <td>¥${item.price.toFixed(2)}</td>
                <td>
                    <div class="quantity-control">
                        <button class="decrease" data-index="${index}">-</button>
                        <input type="text" value="${item.quantity}" readonly>
                        <button class="increase" data-index="${index}">+</button>
                    </div>
                </td>
                <td>¥${subtotal.toFixed(2)}</td>
                <td><span class="remove-item" data-index="${index}">删除</span></td>
            `;
            cartItemsList.appendChild(tr);
        });
        
        // 更新总价显示
        cartTotal.textContent = `¥${total.toFixed(2)}`;
    }
    
    // 统一绑定事件监听器（放在条件判断外部）
    bindCartItemEvents();
}

// 新增：单独的事件绑定函数
function bindCartItemEvents() {
    // 移除旧的监听器（避免重复绑定）
    const removeOldListeners = (selector) => {
        document.querySelectorAll(selector).forEach(btn => {
            btn.replaceWith(btn.cloneNode(true));
        });
    };
    
    removeOldListeners('.decrease');
    removeOldListeners('.increase');
    removeOldListeners('.remove-item');
    
    // 绑定新监听器
    document.querySelectorAll('.decrease').forEach(btn => {
        btn.addEventListener('click', function() {
            const index = parseInt(this.getAttribute('data-index'));
            decreaseQuantity(index);
        });
    });
    
    document.querySelectorAll('.increase').forEach(btn => {
        btn.addEventListener('click', function() {
            const index = parseInt(this.getAttribute('data-index'));
            increaseQuantity(index);
        });
    });
    
    document.querySelectorAll('.remove-item').forEach(btn => {
        btn.addEventListener('click', function() {
            const index = parseInt(this.getAttribute('data-index'));
            removeItem(index);
        });
    });
}

// 增加商品数量
function increaseQuantity(index) {
    cartItems[index].quantity++;
    updateCartDisplay();
}

// 减少商品数量
function decreaseQuantity(index) {
    if (cartItems[index].quantity > 1) {
        cartItems[index].quantity--;
    } else {
        // 数量为1时减少变为移除商品
        removeItem(index);
        return; // 直接返回，updateCartDisplay已在removeItem中调用
    }
    updateCartDisplay();
}

// 移除商品
function removeItem(index) {
    cartItems.splice(index, 1);
    updateCartDisplay(); // 确保UI同步更新
}

// 添加商品到购物车
addToCartButtons.forEach(button => {
    button.addEventListener('click', function() {
        const productCard = this.closest('.product-card');
        const productName = productCard.querySelector('h4').textContent;
        const productPrice = parseFloat(productCard.querySelector('.price').textContent.replace('¥', ''));
        const productImage = productCard.querySelector('img').src;
        
        // 检查是否已存在相同商品
        const existingItem = cartItems.find(item => item.name === productName);
        
        if (existingItem) {
            existingItem.quantity++;
        } else {
            cartItems.push({
                name: productName,
                price: productPrice,
                image: productImage,
                quantity: 1
            });
        }
        
        // 更新显示
        updateCartDisplay();
        
        // 添加动画效果
        this.textContent = '已添加';
        this.style.backgroundColor = '#4CAF50';
        
        setTimeout(() => {
            this.textContent = '加入购物车';
            this.style.backgroundColor = '#f5f5f5';
        }, 1000);
    });
});

// 购物车链接点击事件
document.querySelector('.cart a').addEventListener('click', function(e) {
    e.preventDefault();
    showCartPage();
});

// 继续购物按钮
continueShoppingBtn.addEventListener('click', function(e) {
    e.preventDefault();
    hideCartPage();
});

// 结算按钮
checkoutBtn.addEventListener('click', function() {
    alert('结算功能需要后端支持，这里仅做演示');
});

// 点击购物车页面外部关闭
document.getElementById('cart-page').addEventListener('click', function(e) {
    if (e.target === this) {
        hideCartPage();
    }
});

    // 倒计时功能
    function updateCountdown() {
        const timeLeftElements = document.querySelectorAll('.time-left');
        
        timeLeftElements.forEach(element => {
            let text = element.textContent;
            let timeMatch = text.match(/(\d+)天 (\d+):(\d+):(\d+)/);
            
            if (timeMatch) {
                let days = parseInt(timeMatch[1]);
                let hours = parseInt(timeMatch[2]);
                let minutes = parseInt(timeMatch[3]);
                let seconds = parseInt(timeMatch[4]);
                
                // 减少1秒
                seconds--;
                
                if (seconds < 0) {
                    seconds = 59;
                    minutes--;
                    
                    if (minutes < 0) {
                        minutes = 59;
                        hours--;
                        
                        if (hours < 0) {
                            hours = 23;
                            days--;
                            
                            if (days < 0) {
                                // 倒计时结束
                                element.textContent = '活动已结束';
                                return;
                            }
                        }
                    }
                }
                
                // 更新显示
                element.textContent = `剩余时间: ${days}天 ${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
            }
        });
    }
    
    // 每秒更新一次倒计时
    setInterval(updateCountdown, 1000);

    // 表单提交
    const loginForm = document.getElementById('login-form');
    
    if (loginForm) {
        loginForm.addEventListener('submit', function(e) {
            e.preventDefault();
            alert('登录功能需要后端支持，这里仅做演示');
            loginModal.style.display = 'none';
        });
    }
});

// 购物车功能增强
let cartPage = document.getElementById('cart-page');
let startY, currentY;

function showCartPage() {
    cartPage.style.display = 'block';
    setTimeout(() => {
        cartPage.classList.add('active');
    }, 10);
    
    updateCartDisplay();
}

function hideCartPage() {
    cartPage.classList.remove('active');
    setTimeout(() => {
        cartPage.style.display = 'none';
    }, 300);
}

// 关闭按钮
document.querySelector('.close-cart').addEventListener('click', hideCartPage);

// 遮罩层点击关闭
document.querySelector('.cart-overlay').addEventListener('click', hideCartPage);

// 触摸滑动关闭
cartPage.addEventListener('touchstart', function(e) {
    if (e.target.closest('.cart-content') && e.touches[0].clientY < 100) {
        startY = e.touches[0].clientY;
    }
}, { passive: true });

cartPage.addEventListener('touchmove', function(e) {
    if (!startY) return;
    currentY = e.touches[0].clientY;
    const deltaY = currentY - startY;
    
    if (deltaY > 0) {
        e.preventDefault();
        const progress = Math.min(deltaY / 200, 1);
        document.querySelector('.cart-container').style.transform = `translateY(${-100 + progress * 100}%)`;
        document.querySelector('.cart-overlay').style.opacity = 1 - progress;
    }
}, { passive: false });

cartPage.addEventListener('touchend', function() {
    if (!startY) return;
    
    if (currentY - startY > 100) {
        hideCartPage(); 
    } else {
        document.querySelector('.cart-container').style.transform = 'translateY(-100%)';
        document.querySelector('.cart-overlay').style.opacity = 1;
    }
    startY = null;
});


// 右下角工具栏功能
document.addEventListener('DOMContentLoaded', function() {
  // 回到顶部按钮
  const backToTop = document.getElementById('back-to-top');
  backToTop.addEventListener('click', function() {
    window.scrollTo({
      top: 0,
      behavior: 'smooth'
    });
  });
  
  // 显示/隐藏回到顶部按钮
  window.addEventListener('scroll', function() {
    if (window.pageYOffset > 300) {
      backToTop.style.display = 'flex';
    } else {
      backToTop.style.display = 'none';
    }
  });

  // 联系客服按钮
  const customerService = document.getElementById('customer-service');
  const servicePopup = document.getElementById('service-popup');
  const closePopup = document.querySelector('.close-popup');
  
  customerService.addEventListener('click', function() {
    servicePopup.style.display = 'block';
  });
  
  closePopup.addEventListener('click', function() {
    servicePopup.style.display = 'none';
  });
  
  // 点击浮窗选项
  document.querySelectorAll('.service-option').forEach(option => {
    option.addEventListener('click', function() {
      const text = this.querySelector('span').textContent;
      if (text === '950800') {
        window.location.href = 'tel:950800';
      } else if (text === '在线咨询') {
        window.open('https://consumer.huawei.com/cn/contact-us/', '_blank');
      } else {
        window.open('https://consumer.huawei.com/cn/support/', '_blank');
      }
      servicePopup.style.display = 'none';
    });
  });
  
  // 点击外部关闭浮窗
  document.addEventListener('click', function(e) {
    if (!servicePopup.contains(e.target) && e.target !== customerService) {
      servicePopup.style.display = 'none';
    }
  });
});